﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Linq;
using VisionCloud.Domain.Filters;

namespace VisionSurface.Web.Extensions
{
    public static class SwaggerExtensions
    {
        public static readonly string[] docs = new[] { "任务管理", "项目管理", "微信消息推送","文件管理" };

        private static IServiceCollection AddCustomSwagger(this IServiceCollection services, string[] docs)
        {
            services.AddSwaggerGen(c =>
            {
                foreach (var doc in docs)
                    c.SwaggerDoc(doc, new OpenApiInfo
                    {
                        Version = doc,
                        Title = doc
                    });
                c.EnableAnnotations();
                c.IgnoreObsoleteProperties(); // Obsolete接口划删除线
                c.CustomSchemaIds(a => a.FullName);

                var basePath = Path.GetDirectoryName(AppContext.BaseDirectory);
                var files = Directory.GetFiles(basePath).Where(a => Path.GetExtension(a) == ".xml");
                foreach (var file in files)
                {
                    c.IncludeXmlComments(file, true); // 加载生成XML文件
                }

                c.SchemaFilter<EnumSchemaFilter>();
            });

            return services;
        }

        /// <summary>
        /// 注入swagger
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddCustomSwagger(this IServiceCollection services)
        {
            return services.AddCustomSwagger(docs);
        }

        /// <summary>
        /// 使用swagger
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app)
        {
            app.UseCustomSwagger(docs);
            return app;
        }

        private static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app, string[] docs)
        {
            app.UseSwaggerUI(c =>
            {
                c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None); // 默认折叠
                foreach (var doc in docs)
                    c.SwaggerEndpoint($"/swagger/{doc}/swagger.json", doc);
            }).UseSwagger();
            return app;
        }
    }
}
